package com.jyy.prefabricated.security;



import com.jyy.prefabricated.entity.SysUser;
import com.jyy.prefabricated.enums.BaseStatusEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.jwt.JwtUser;
import com.jyy.prefabricated.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;


@Slf4j
@Component("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if(StringUtils.isBlank(username)){
            throw new CustomException("用户名不能为空！");
        }
        SysUser user = userService.selectByUsernameOrIdCard(username);
        if(user == null){
            throw new CustomException("用户或密码错误！");
        }
        //判断用户是否冻结
        if(user.getStatus().equals(BaseStatusEnum.INVALID.getValue())){
            throw new CustomException("用户已冻结");
        }

        return new JwtUser(username,user.getPassword(),
                true,//账户可用
                AuthorityUtils.commaSeparatedStringToAuthorityList("Browser"));
    }
}
